package com.web.controller;

import com.util.SessionUtils;
import com.web.response.Result;
import com.web.service.UserInfoService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * @author yangguanzan
 * @date 9/20/21
 * @description
 */
@Controller
@RequestMapping("/login")
public class LoginController {

    @Autowired
    UserInfoService userInfoService;


    @RequestMapping(value =  {"/",""} , method = RequestMethod.GET)
    public String loginPage(HttpServletRequest req) {
        //先判断是否存在已登陆的session
        if (SessionUtils.hasUserSession(req.getSession(false))) {
            //存在则重定向到主页
            return "redirect:/hospital/index";
        }
        //不存在则进入登录页
        return "login";
    }

    @PostMapping(value =  {"/",""})
    public String login(ModelMap model,HttpServletRequest req, HttpServletResponse resp,
        @ModelAttribute("username") String username,String password,
        String verifyCode,Boolean rememberMe) {
        // 调用登录服务
        Result result = userInfoService.login(resp,req.getSession(false),
            username,password,verifyCode,rememberMe);
        // 登录成功
        if(result.isSuccess()) {
            // 重定向到主页
            model.clear();
            return "redirect:/hospital/index";
        }
        // 设置错误提示
        model.addAttribute("msg",result.getMsg());
        return "login";
    }

}
